<template>
  <div class="login-containers">
    <transition name="el-zoom-in-center">
      <el-form
        v-show="formShow"
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        style="text-align: center"
        autocomplete="on"
        label-position="left"
      >
        <!--标题-->
        <div class="title-container">
          <div class="title" style="font-size: 26px; font-weight: bold; text-align: center; margin: 0 0 30px 0;">{{ titleText }}</div>
        </div>
        <!--用户名-->
        <el-form-item prop="username">
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="用户名"
            tabindex="1"
          >
            <i slot="prefix">
              <svg-icon icon-class="user" style="color: rgb(64,158,255);" />
            </i>
          </el-input>
        </el-form-item>
        <!--密码-->
        <el-form-item prop="password">
          <el-input
            ref="password"
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            tabindex="2"
            show-password
            @keyup.enter.native="isRegister ? '' : handleVerify()"
          >
            <i slot="prefix">
              <svg-icon icon-class="password" style="color: rgb(64,158,255);" />
            </i>
          </el-input>
        </el-form-item>
        <!--确认密码-->
        <el-form-item v-show="isRegister" prop="password2">
          <el-input
            ref="password2"
            v-model="loginForm.password2"
            type="password"
            placeholder="密码"
            tabindex="3"
            show-password
            @keyup.enter.native="isRegister ? handleVerify() : ''"
          >
            <i slot="prefix">
              <svg-icon icon-class="password" style="color: rgb(64,158,255);" />
            </i>
          </el-input>
        </el-form-item>
        <!--表单提交登录按钮-->
        <div>
          <el-button
            :loading="loading"
            class="login-submit"
            type="primary"
            style="margin-bottom:10px; width: 100%;"
            @click.native.prevent="handleVerify"
          >
            {{ titleText }}
          </el-button>
        </div>
        <!--其他登录方式-->
        <div>
          <!--<el-button-->
          <!--  class="thirdparty-button"-->
          <!--  type="text"-->
          <!--  @click="showDialog=true"-->
          <!--&gt;-->
          <!--  其他方式{{ titleText }}-->
          <!--</el-button>-->
          <el-button type="text">忘记密码</el-button>
          <el-button v-show="!isRegister" type="text" @click="handleToggle">注册</el-button>
          <el-button v-show="isRegister" type="text" @click="handleToggle">去登陆</el-button>
        </div>
      </el-form>
    </transition>
    <!--图形验证码对话框-->
    <el-dialog title="行为验证" :visible.sync="dialogVerifyVisible" width="370px">
      <verify
        :captcha-type="'blockPuzzle'"
        :mode="'fixed'"
        :img-size="{ width: '330px', height: '155px' }"
        @success="isRegister ? handleRegister() : handleLogin()"
      />
    </el-dialog>
  </div>
</template>

<script>
import Verify from '@/components/verifition/Verify'
import { register, validUsername } from '@/api/user'

export default {
  name: 'Index',
  components: { Verify },
  data() {
    const passWord = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.loginForm.password2 !== '') {
          this.$refs.loginForm.validateField('psword')
        }
        callback()
      }
    }
    const passWord2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.loginForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const username = (rule, value, callback) => {
      if (!this.isRegister) {
        return callback()
      }
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else {
        validUsername(this.loginForm.username).then(() => {
          callback()
        }).catch(() => {
          callback(new Error('用户名已存在'))
        })
      }
    }
    return {
      formShow: false,
      // 登陆表单
      loginForm: {
        username: '',
        password: '',
        password2: ''
      },
      // 登录表单规则
      loginRules: {
        username: [
          { required: true, validator: username, trigger: 'blur' },
          { required: true, min: 6, message: '用户名长度不能少于6位' }
        ],
        password: [
          { required: true, validator: passWord, trigger: 'blur' },
          { required: true, min: 6, trigger: 'blur', message: '密码长度不能少于6位' }
        ],
        password2: [
          { required: true, validator: passWord2, trigger: 'blur' },
          { required: true, min: 6, trigger: 'blur', message: '密码长度不能少于6位' }
        ]
      },
      // 加载动画
      loading: false,
      redirect: undefined,
      otherQuery: {},
      // 注册行为
      isRegister: false,
      // 登陆表单标题
      titleText: '登录',
      // 验证码对话框
      dialogVerifyVisible: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    this.formShow = true
    if (this.$store.getters.isRegister) {
      this.handleToggle()
    }
    this.$store.commit('user/SET_IS_REGISTER', false)
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    // 登录或注册时的行为验证码
    handleVerify() {
      if (this.isRegister) {
        // 注册
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            // 表单校验通过
            this.dialogVerifyVisible = true
          }
        })
      } else {
        // 登录
        this.$refs.loginForm.validateField(['username', 'password'], valid => {
          if (!valid) {
            // 表单校验通过
            this.dialogVerifyVisible = true
          }
        })
      }
    },
    // 登录事件
    handleLogin() {
      this.dialogVerifyVisible = false
      this.loading = true
      this.$store.dispatch('user/login', this.loginForm)
        .then(() => {
          this.$router.push({ path: this.redirect || '/index', query: this.otherQuery })
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 注册事件
    handleRegister() {
      // 关闭行为验证码
      this.dialogVerifyVisible = false
      register(this.loginForm).then(res => {
        this.$notify.success({
          title: '成功',
          message: res.data,
          duration: 1000
        })
        this.handleToggle()
      }).catch(() => {
        this.$refs.loginForm.resetFields()
      })
    },
    // 注册登录切换事件
    handleToggle() {
      this.formShow = false
      this.isRegister = !this.isRegister
      this.titleText = this.titleText === '登录' ? '注册' : '登录'
      setTimeout(() => {
        this.formShow = true
        this.$refs.loginForm.resetFields()
      }, 200)
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss" scoped>
.login-containers {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url("../../assets/background-images/elephant.png") no-repeat 50%;
}
.login-form {
  height: 270px;
  width: 300px;
  margin: 5px;
  padding: 10px 0;
}
</style>
